<?php


namespace App\Http\Controllers\FddVerifySDK;


use App\Http\Controllers\BranchUtils;
use App\Models\FddRecord;
use App\Models\Order;
use App\Models\Image;
use App\Models\OrderRecord;
use App\Models\SystemCompanyMessage;
use App\Models\User;
use App\Models\ContractModel;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Controllers\common\LMReturn;

include_once 'Fdd.Config.php';


class FddApiInterface extends Controller
{
    const verified_way_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
    // 用户实名认证接口
    public function UserRegistered(Request $request) {
        // 去验证token值
        $tokenInfo = json_decode($this->verifyTokenLm(), true);
        //判断传递过来的token的code码是否等于400  如果是400的话，提示token不正确
        if ($tokenInfo['code'] == 400) {
            return LMReturn::Error($tokenInfo['msg'], $tokenInfo['code']);
        }
        if (isset($tokenInfo['worker_id'])) {
            $worker_id = $tokenInfo['worker_id'];
            $all = $request->all();
            if (isset($all['user_id'])) {
                $user_id = $all['user_id'];
            } else {
                return LMReturn::Error('未传入用户id');
            }
//            if (FddUtils::IsUserBelongToWorker($user_id, $worker_id) == false) {
//                return LMReturn::Error('抱歉，非所属客户无法进行此操作');
//            }
        } elseif (isset($tokenInfo['user_id'])) {
            $user_id = $tokenInfo['user_id'];
        } else {
            return LMReturn::Error('无法认证');
        }
        $cert_type = '0';
        $customer_ident_type = '0';
        if (isset($all['id_type'])) {
            if ($all['id_type'] != '0') {
                $customer_ident_type = '1';
                $cert_type = $all['id_type'];
            }
        }
        $cert_flag = 1;
        $user = User::find($user_id);
        if (empty($user)) {
            return LMReturn::Error('抱歉没有该用户');
        }
        if ($user->contact_manner == null) {
            return LMReturn::Error('请先为用户添加手机号');
        }
        if (isset($all['verified_way']) && in_array($all['verified_way'], FddApiInterface::verified_way_list)) {
            $verified_way = $all['verified_way'];
        } else {
            $verified_way = '0';
        }
        if (isset($all['page_modifyh']) && in_array($all['page_modifyh'], ['1', '2'])) {
            $page_modifyh = $all['page_modifyh'];      // 是否允许用户页面修改 1允许 2不允许
        } else {
            $page_modifyh = '1';
        }
        // 得到用户在法大大的唯一标识'6256D1231368F8A0543F180581AA7452'需要入库
        try {
            $data = FddUserUtils::FddUserRegistered($user_id);
            $customer_id = $data['data'];
            $user->customer_id = $customer_id;
            $user->save();
            $id_number = $user->id_number;
            if ($id_number != null) {
                $customer_ident_no = $id_number;
            } else {
                $customer_ident_no = null;
            }
            $image = Image::where('user_id', $user->id)->where('img_type', 1)->first();
            if ($image) {
                $ident_path = $image->url;
            } else {
                $ident_path = null;
            }
            $baseCode = FddUserUtils::FddUserVerify($customer_id, $verified_way, $page_modifyh, $user->name, $customer_ident_type, $cert_type, $customer_ident_no, $user->contact_manner, $ident_path, $cert_flag);
            $code = $baseCode['code'];
            if ($code == 1) {
                $href = base64_decode($baseCode['data']['url']);
                $transaction = $baseCode['data']['transactionNo'];
                $user = User::find($user_id);
                $user->verified_serialno = $transaction;
                $user->save();
                return FddUserUtils::SendMassage($href, $user->contact_manner, 2);
            } else {
                return $baseCode;
            }
        } catch (\Throwable $th) {
            return LMReturn::Error();
        }
    }

    // 用户实名认证回调接口
    public function NotifyUrl(Request $request) {
        $all = $request->all();
        try{
            $sign = $all['sign'];
            $appId = $all['appId'];
            $serialNo = $all['serialNo'];
            $customerId = $all['customerId'];
            $status = $all['status'];
            $statusDesc = $all['statusDesc'];
            if ($statusDesc == 'null' || $statusDesc == null) {
                $statusDesc = '';
            }
            $certStatus = $all['certStatus'];
            $authenticationType = $all['authenticationType'];
            $timestamp = $all['timestamp'];
            $sha1Str = \FddConfig::AppSecret . $authenticationType . $certStatus . $customerId . $serialNo . $status . $statusDesc;
            $encodeSign = base64_encode(strtoupper(sha1(strtoupper($appId) . strtoupper(md5($timestamp)) . strtoupper(sha1($sha1Str)))));
            $user = User::where('customer_id', $customerId)->first();
            if ($user) {
                $is_pass = FddUserUtils::CompareUserMessage($user->verified_serialno, $user->id);
                if ($is_pass == true) {
                    if ($sign == $encodeSign && $appId == \FddConfig::AppId) {
                        $user->fdd_cert_status = $certStatus;
                        $user->fdd_status = $status;
                    }
                } else {
                    $user->fdd_cert_status = 0;
                    $user->fdd_status = 4;
                }
                $user->save();
            }
        } catch (\Throwable $th) {

        }
    }

    // 企业实名认证
    public function CompanyRegistered(Request $request) {
        // 去验证token值
        $tokenInfo = json_decode($this->verifyTokenLm(), true);
        //判断传递过来的token的code码是否等于400  如果是400的话，提示token不正确
        if ($tokenInfo['code'] == 400) {
            return LMReturn::Error($tokenInfo['msg'], $tokenInfo['code']);
        }
        $worker_id = $tokenInfo['worker_id'];
        $all = $request->all();
        if (isset($all['company_id'])) {
            $company_id = $all['company_id'];
        } else {
            $company_id = 1;
        }
        if (FddUtils::IsWorkerRole($worker_id) == true) {
            return FddUserUtils::FddCompanyVerify($company_id);
        } else {
            return LMReturn::Error('抱歉您不是超级管理员，没有此权限');
        }
    }

    // 企业实名信息
    public function CompanyMessage(Request $request) {
        // 去验证token值
        $tokenInfo = json_decode($this->verifyTokenLm(), true);
        //判断传递过来的token的code码是否等于400  如果是400的话，提示token不正确
        if ($tokenInfo['code'] == 400) {
            return LMReturn::Error($tokenInfo['msg'], $tokenInfo['code']);
        }
        $worker_id = $tokenInfo['worker_id'];
        $all = $request->all();
        if (FddUtils::IsWorkerRole($worker_id) == true) {
            if (isset($all['company_id'])) {
                return json_decode(SystemCompanyMessage::find($all['company_id']), true);
            }
            if (env('COMPANY') == 3) {
                $company_list = [1,2,3,4,7];
            } else {
                $company_list = [1];
            }
            return json_decode(SystemCompanyMessage::whereIn('id', $company_list)->get(), true);
        } else {
            return LMReturn::Error('抱歉您不是超级管理员，没有此权限');
        }
    }

    // 企业实名认证回调
    public function CompanyNotifyUrl(Request $request) {
        // 直接去法大大查询企业实名认证信息，所以不需要验证回调是否真实
        $all = $request->all();
        $serialNo = $all['serialNo'];
        FddUserUtils::UploadCompanyMessage($serialNo);
    }

    // 合同模板在线编辑,上传生成可编辑文件
    public function uploadModelInLine(Request $request) {
        // 去验证token值
        $tokenInfo = json_decode($this->verifyTokenLm(), true);
        //判断传递过来的token的code码是否等于400  如果是400的话，提示token不正确
        if ($tokenInfo['code'] == 400) {
            return LMReturn::Error($tokenInfo['msg'], $tokenInfo['code']);
        }
        $all = $request->all();
        if (isset($all['contract_id'])) {
            // 修改
            $contract_id = $all['contract_id'];
            $contract = ContractModel::find($contract_id);
            if ($contract->is_able == 1) {
                return LMReturn::Error('使用中模板，不可编辑');
            }
            return FddUserUtils::UploadTemplate($contract_id);
        } else {
            // 创建合同模板
            if (isset($all['product_class_id'])) {
                $product = $all['product_class_id'];
            } else {
                $product = null;
            }
            if (isset($all['template_type']) && $all['template_type'] == 1) {
                $template_type = 1;
            } else {
                $template_type = 2;
            }
            if (isset($all['title'])) {
                $title = $all['title'];
            } else {
                return LMReturn::Error('未传入合同模板标题');
            }
            //判断文件格式
            $file = $request->file('pdf');
            if (empty($file)) {
                return back()->withInput()->with('questionError', '请上传需转换文件');
            }
            if (!in_array($file->getClientOriginalExtension(), ['pdf', 'PDF'])) {
                return back()->withErrors(['import' => '文件仅支持pdf'])->withInput();
            }
            //获取文件
            $fileName = 'C' . $tokenInfo['worker_id'] . time() . '.' . $file->getClientOriginalExtension();
            $filePath = public_path('pdf_files/' . date("Ymd") . '/');
            $file->move($filePath, $fileName);
            // 添加
            try {
                $contract = new ContractModel();
                $contract->product_class_id = $product;
                $contract->title = $title;
                $contract->is_able = 0;
                $contract->is_upload = 1;
                $contract->file_path = $filePath.$fileName;
                $contract->template_type = $template_type;
                $contract->save();
            } catch (\Throwable $th) {
                return LMReturn::Error('请传入正确的产品分类id');
            }
            $contract_id = $contract->id;
            return FddUserUtils::FddContractModel($contract_id, $filePath.$fileName);
        }
    }

    // 上传不可编辑合同模板
    public function uploadAbleModelInLine(Request $request) {
        // 去验证token值
        $tokenInfo = json_decode($this->verifyTokenLm(), true);
        //判断传递过来的token的code码是否等于400  如果是400的话，提示token不正确
        if ($tokenInfo['code'] == 400) {
            return LMReturn::Error($tokenInfo['msg'], $tokenInfo['code']);
        }
        $all = $request->all();
        if (isset($all['product_class_id'])) {
            $product = $all['product_class_id'];
        } else {
            $product = null;
        }
        if (isset($all['template_type']) && $all['template_type'] == 1) {
            $template_type = 1;
        } else {
            $template_type = 2;
        }
        if (isset($all['title'])) {
            $title = $all['title'];
        } else {
            return LMReturn::Error('未传入合同模板标题');
        }
        //判断文件格式
        $file = $request->file('pdf');
        if (empty($file)) {
            return back()->withInput()->with('questionError', '请上传需转换文件');
        }
        if (!in_array($file->getClientOriginalExtension(), ['pdf', 'PDF'])) {
            return back()->withErrors(['import' => '文件仅支持pdf'])->withInput();
        }
        //获取文件
        $fileName = 'C' . $tokenInfo['worker_id'] . time() . '.' . $file->getClientOriginalExtension();
        $filePath = public_path('able_pdf_files/' . date("Ymd") . '/');
        $file->move($filePath, $fileName);
        // 添加
        try {
            $contract = new ContractModel();
            $contract->product_class_id = $product;
            $contract->title = $title;
            $contract->is_able = 0;
            $contract->is_upload = 0;
            $contract->file_path = $filePath.$fileName;
            $contract->template_type = $template_type;
            $contract->save();
        } catch (\Throwable $th) {
            return LMReturn::Error('请传入正确的产品分类id');
        }
        $contract_id = $contract->id;
        return FddUserUtils::FddContractAbleModel($contract_id, $filePath.$fileName);
    }

    // 设置为可使用模板
    public function SetAbleModel(Request $request) {
        // 去验证token值
        $tokenInfo = json_decode($this->verifyTokenLm(), true);
        //判断传递过来的token的code码是否等于400  如果是400的话，提示token不正确
        if ($tokenInfo['code'] == 400) {
            return LMReturn::Error($tokenInfo['msg'], $tokenInfo['code']);
        }
        $all = $request->all();
        if (isset($all['template_id'])) {
            $template_id = $all['template_id'];
        } else {
            return LMReturn::Error('未选择模板id');
        }
        $template = ContractModel::find($template_id);
        if ($template) {
            if ($template->is_able == 0) {
                $template->is_able = 1;
            } else {
                $template->is_able = 0;
            }
            $template->save();
            return LMReturn::Success();
        } else {
            return LMReturn::Error('没有该模板');
        }
    }

    // 查看合同模板接口
    public function SeleContractModel(Request $request) {
        // 去验证token值
        $tokenInfo = json_decode($this->verifyTokenLm(), true);
        //判断传递过来的token的code码是否等于400  如果是400的话，提示token不正确
        if ($tokenInfo['code'] == 400) {
            return LMReturn::Error($tokenInfo['msg'], $tokenInfo['code']);
        }
        $all = $request->all();
        if (empty($all['template_id'])) {
            return LMReturn::Error('未选择模板');
        }
        $url = FddUserUtils::SeleContract($all['template_id']);
        return ['code'=>200, 'msg'=>'成功', 'data'=>$url];
    }

    // 删除合同模板接口
    public function DeleteTemplate(Request $request) {
        // 去验证token值
        $tokenInfo = json_decode($this->verifyTokenLm(), true);
        //判断传递过来的token的code码是否等于400  如果是400的话，提示token不正确
        if ($tokenInfo['code'] == 400) {
            return LMReturn::Error($tokenInfo['msg'], $tokenInfo['code']);
        }
        $all = $request->all();
        if (empty($all['template_id'])) {
            return LMReturn::Error('未选择模板');
        }
        $template = ContractModel::find($all['template_id']);
        if ($template) {
            // 需要判断，有已生效订单或使用中模板不可被删除
            $result = FddUserUtils::DeleteContract($all['template_id']);
            if ($result['code'] == 1) {
                $template->delete();
                return LMReturn::Success();
            } else {
                return $result;
            }
        } else {
            return LMReturn::Error('没有该模板');
        }
    }

    // 合同模板列表
    public function TemplateList(Request $request) {
        // 去验证token值
        $tokenInfo = json_decode($this->verifyTokenLm(), true);
        //判断传递过来的token的code码是否等于400  如果是400的话，提示token不正确
        if ($tokenInfo['code'] == 400) {
            return LMReturn::Error($tokenInfo['msg'], $tokenInfo['code']);
        }
        $all = $request->all();
        $where = [];
        $product_class_list = [];
        if (isset($all['product_class'])) {
            $product_class_list = $all['product_class'];
        }
        if (isset($all['template_type'])) {
            $where['template_type'] = $all['template_type'];
        }
        if (isset($all['is_able'])) {
            $where['is_able'] = $all['is_able'];
        }
        if (isset($all['is_upload'])) {
            $where['is_upload'] = $all['is_upload'];
        }
        $page = $all['page'] ?? 1;
        $size = $all['size'] ?? 15;
        $templates = ContractModel::select(
            'contract_model.id',
            'contract_model.title',
            'contract_model.is_able',
            'contract_model.is_upload',
            'contract_model.template_type',
            'product_class.category_name as product_class_name',
            'product_class.id as product_class_id'
        )->when(count($product_class_list) > 0, function ($query) use ($product_class_list) {
            return $query->whereIn('product_class_id', $product_class_list);
            })
            ->when(isset($all['product_id']), function ($query) use ($all) {
                $product_id = $all['product_id'];
                return $query->whereHas('product_class', function ($product_class_query) use ($product_id) {
                    $product_class_query->whereHas('products', function ($product_query) use ($product_id) {
                        $product_query->where('id', $product_id);
                    });
                });
            })
            ->where($where)
            ->leftjoin("product_class", "contract_model.product_class_id", "=", "product_class.id")
            ->get();
        return json_decode($templates);
    }

    // 合同模板下载
    public function DownloadTemplate(Request $request) {
        // 去验证token值
        $tokenInfo = json_decode($this->verifyTokenLm(), true);
        //判断传递过来的token的code码是否等于400  如果是400的话，提示token不正确
        if ($tokenInfo['code'] == 400) {
            return LMReturn::Error($tokenInfo['msg'], $tokenInfo['code']);
        }
        $all = $request->all();
        if (isset($all['template_id'])) {
            return FddUserUtils::DownloadContract($all['template_id']);
        } else {
            return LMReturn::Error('未传入模板');
        }
    }

    // 合同模板填充界面(暂时弃用)
    public function FileTemplate(Request $request) {
        // 去验证token值
        $tokenInfo = json_decode($this->verifyTokenLm(), true);
        //判断传递过来的token的code码是否等于400  如果是400的话，提示token不正确
        if ($tokenInfo['code'] == 400) {
            return LMReturn::Error($tokenInfo['msg'], $tokenInfo['code']);
        }
        $all = $request->all();
        $template_id = $all['template_id'];
        $contract_id = $all['contract_id'];
        return FddUserUtils::FileContractUrl($template_id, $contract_id);
//        if (isset($all['user_id'])) {
//            $user = User::find($all['user_id']);
//            if ($user) {
//                $fdd_status = $user->fdd_status;
//                if ($fdd_status != 2) {
//                    return LMReturn::Error('该用户未实名认证，无法进行电子签约');
//                }
//                $customer_id = $user->customer_id;
//
//            } else {
//                return LMReturn::Error('没有该用户');
//            }
//        }
    }

    // 查看/下载合同
    public function SeleContract(Request $request) {
        // 去验证token值
        $tokenInfo = json_decode($this->verifyTokenLm(), true);
        //判断传递过来的token的code码是否等于400  如果是400的话，提示token不正确
        if ($tokenInfo['code'] == 400) {
            return LMReturn::Error($tokenInfo['msg'], $tokenInfo['code']);
        }
        $all = $request->all();
        if (isset($all['contract_id'])) {
//            if (isset($tokenInfo['worker_id'])) {
//                if (FddUtils::IsOrderBelongToWorker($all['contract_id'], $tokenInfo['worker_id']) == false) {
//                    return LMReturn::Error('非所属订单不可进行此操作');
//                }
//            } elseif (isset($tokenInfo['user_id'])) {
//                if (FddUtils::IsOrderBelongToUser($all['contract_id'], $tokenInfo['user_id']) == false) {
//                    return LMReturn::Error('非所属订单不可进行此操作');
//                }
//            } else {
//                return LMReturn::Error('登录信息有误');
//            }
            $order = Order::find($all['contract_id']);
            $contract_id = $order['order_no'];
            if (isset($all['type']) && $all['type'] == 2) {
                return FddUserUtils::CheckContract($contract_id, 2);
            } else {
                return FddUserUtils::CheckContract($contract_id, 1);
            }
        } else {
            return LMReturn::Error('未传入合同id');
        }
    }

    // 合同模板填充
    public function FileContract(Request $request) {
        // 去验证token值
        $tokenInfo = json_decode($this->verifyTokenLm(), true);
        //判断传递过来的token的code码是否等于400  如果是400的话，提示token不正确
        if ($tokenInfo['code'] == 400) {
            return LMReturn::Error($tokenInfo['msg'], $tokenInfo['code']);
        }
        $worker_id = $tokenInfo['worker_id'];
        $all = $request->all();
        $is_sms = $all['is_sms'] ?? 1;
        if (isset($all['order_id'])) {
            $order_id = $all['order_id'];
        } else {
            return LMReturn::Error('未传入订单id');
        }
//        if (FddUtils::IsOrderBelongToWorker($order_id, $worker_id) == false) {
//            return LMReturn::Error('非所属订单不可进行此操作');
//        }
        if (isset($all['template_id'])) {
            $template_id = $all['template_id'];
        } else {
            return LMReturn::Error('请选择合同模板');
        }
        $order_data = [];
        if (isset($all['sign_add']) && $all['sign_add'] != '' && $all['sign_add'] != null) {
            $order_data['sign_add'] = $all['sign_add'];
        } else {
            $order_data['sign_add'] = '测试默认地点';
        }
        try {
            $template = ContractModel::find($template_id);
            if ($template->is_able != 1) {
                return LMReturn::Error('非启用模板，不可使用');
            }
            if (env('COMPANY') == 3) {
                $order = Order::find($order_id);
                $branch = $order['president_id'];
                if ($branch == '国逸') {
                    $sys_id = 2;
                } elseif ($branch == '安盛') {
                    $sys_id = 3;
                } elseif ($branch == '逸盛') {
                    $sys_id = 4;
                } elseif ($branch == null) {
                    $sys_id = 1;
                } else {
                    $sys_id = BranchUtils::selePbranch($order['branch_id']);
                }
            } else {
                $sys_id = 1;
            }
            $company_data = SystemCompanyMessage::find($sys_id);
            $order = Order::where('id', $order_id)->with('product.product_class')->with('user')->with('bank_card.bank')->first();
            if ($order->fdd_sign_status == 1) {
                return LMReturn::Error('该合同已签署电子合同，不可重复签署');
            } elseif ($order->fdd_sign_status == 4) {
                if ($is_sms == 1) {
                    // 给客户发送手动签署链接短信
                    $result = FddUserUtils::ExtsignWay($order_id);
                    if ($result['code'] == 200) {
                        $order = Order::find($order_id);
                        $order->fdd_sign_status = 3;
                        $order->save();
                        return ['code'=>200, 'msg'=>$result['msg']];
                    } else {
                        return $result;
                    }
                } else {
                    return LMReturn::Error('合同已生成');
                }
            } elseif ($order->fdd_sign_status == 5) {
                return LMReturn::Error('订单已被拒签或签署失败，请创建新订单进行电子签约');
            } elseif ($order->fdd_sign_status == 3 || $order->fdd_sign_status == 6) {
                return LMReturn::Error('订单签署正在进行中，请静待结果');
            }
            if ($template->product_class_id != $order['product']['product_class']['id']) {
                return LMReturn::Error('抱歉，您选择的模板不符合该产品');
            } else {
                $order->template_id = $template_id;
                $order->save();
            }
            $order_data['user_name'] = $order['user']['name'];
            $order_data['user_tel'] = $order['user']['contact_manner'];
            $order_data['user_add'] = $order['user']['address'] ?? '';
            $order_data['user_card_type'] = $order['user']['id_type'];
            $order_data['user_id_number'] = $order['user']['id_number'];
            $order_data['user_email'] = $order['user']['email'] ?? '';
            $order_data['user_open_bank'] = $order['bank_card']['bank_sum_name'];
            $order_data['user_bank_name'] = $order['bank_card']['bank']['bank_name'];
            $order_data['user_bank_card_id'] = $order['bank_card']['bank_num'];
            $order_data['user_bank_account_name'] = $order['bank_card']['account_name'];
            $order_data['user_bank_phone'] = $order['bank_card']['phone_num'] ?? '';
            $order_data['product_name'] = $order['product']['name'];
            $order_data['long_time'] = $order['product']['long_time'];
            $order_data['long_time_str'] = $order['product']['long_time'] . '个月';
            $order_data['rate'] = $order['product']['rate'];
            $order_data['rate_str'] = $order['product']['rate'] . '%';
            if ($order['product']['pay_long'] == $order['product']['long_time']) {
                $pay_type = '到期付款';
            } else {
                if ($order['product']['pay_long'] == 3) {
                    $pay_type = '按季付款';
                } elseif ($order['product']['pay_long'] == 1) {
                    $pay_type = '按月付款';
                } elseif ($order['product']['pay_long'] == 12) {
                    $pay_type = '按年付款';
                } else {
                    return LMReturn::Error('产品未知的付款方式，请联系管理员');
                }
            }
            $order_data['pay_type'] = $pay_type;
            $order_data['pay_time'] = $order['product']['pay_long'];
            $order_data['pay_time_str'] = $order['product']['pay_long'] . '个月';
            $order_data['order_money'] = $order['order_money'];
            $order_money_zh = FddUtils::convertAmountToCn($order['order_money']);
            $order_data['order_money_zh'] = $order_money_zh;
            $order_data['valid_time'] = $order['sign_time'];
            $order_data['valid_time_year'] = date('Y', strtotime($order['sign_time']));
            $order_data['valid_time_month'] = date('m', strtotime($order['sign_time']));
            $order_data['valid_time_day'] = date('d', strtotime($order['sign_time']));
            $order_data['end_time'] = date('Y年m月d日', strtotime($order['contract_end_date']));
            $order_data['end_time_year'] = date('Y', strtotime($order['contract_end_date']));
            $order_data['end_time_month'] = date('m', strtotime($order['contract_end_date']));
            $order_data['end_time_day'] = date('d', strtotime($order['contract_end_date']));
            $order_data['contract_no'] = $order['contract_no'];
            $order_data['renewal_contract_number'] = $order['renewal_contract_number'] ?? '';
            $now_time = time();
            $order_data['now'] = date('Y年m月d日', $now_time);
            $order_data['now_year'] = date('Y', $now_time);
            $order_data['now_month'] = date('m', $now_time);
            $order_data['now_day'] = date('d', $now_time);
            $order_data['institution_name'] = $company_data['company_name'] ?? '';
            $order_data['institution_No'] = $company_data['organization'] ?? '';
            $order_data['legal_person'] = $company_data['legal_name'] ?? '';
            $order_data['legal_person_tel'] = $company_data['legal_mobile'] ?? '';
            $order_data['institution_email'] = $company_data['company_email'] ?? '';
            // 账户名称，暂用公司名称
            $order_data['institution_account'] = $company_data['company_name'] ?? '';
            $order_data['institution_open_bank'] = $company_data['bank_detail_name'] ?? '';
            $order_data['institution_bank_card_id'] = $company_data['bank_card_no'] ?? '';
        } catch (\Throwable $th) {
            return LMReturn::Error('填充合同所需信息不全，请完善信息！');
        }
        $result = FddUserUtils::GetKeys($template_id);
        if ($result['code'] == 1) {
            $jsons = json_decode($result['data'], true);
            if (count($jsons) > 0) {
                $key_list = [];
                foreach ($jsons as $json) {
                    if (isset($order_data[$json['name']])) {
                        $key_list[$json['key']] = $order_data[$json['name']];
                    } else {
                        return LMReturn::Error('缺少表单域字段，请联系管理员添加');
                    }
                }
                // 开始进行模板填充
                $order_no = time() . $order_id;
                $res = FddUserUtils::FileContract($key_list, $template_id, $order_no);
                if ($res['code'] == 1000) {
                    $order = Order::find($order_id);
                    $order->fdd_sign_status = 4;
                    $order->order_no = $order_no;
                    $order->save();
                    if ($is_sms == 1) {
                        // 给客户发送手动签署链接短信
                        $result = FddUserUtils::ExtsignWay($order_id);
                        if ($result['code'] == 200) {
                            $order = Order::find($order_id);
                            $order->fdd_sign_status = 3;
                            $order->save();
                            return ['code'=>200, 'msg'=>$result['msg'], 'data'=>[]];
                        } else {
                            return $result;
                        }
                    } else {
                        return ['code'=>200, 'msg'=>'已生成填充后的合同，可下载', 'data'=>[]];
                    }
                } else {
                    return $res;
                }
            } else {
                $order = Order::find($order_id);
                $order->fdd_sign_status = 4;
                $order->save();
                if ($is_sms == 1) {
                    $result = FddUserUtils::ExtsignWay($order_id);
                    if ($result['code'] == 200) {
                        $order = Order::find($order_id);
                        $order->fdd_sign_status = 3;
                        $order->save();
                        return ['code'=>200, 'msg'=>$result['msg'], 'data'=>[]];
                    } else {
                        return $result;
                    }
                } else {
                    return ['code'=>200, 'msg'=>'已生成填充后的合同，可下载', 'data'=>[]];
                }
            }
        } else {
            return $result;
        }
    }

    // 合同上传(后续添加),建新表，存其他类型合同，绑定订单等...

    // 手动签署接口
    public function FddExtsign(Request $request) {
        // 去验证token值
        $tokenInfo = json_decode($this->verifyTokenLm(), true);
        //判断传递过来的token的code码是否等于400  如果是400的话，提示token不正确
        if ($tokenInfo['code'] == 400) {
            return LMReturn::Error($tokenInfo['msg'], $tokenInfo['code']);
        }
        $worker_id = $tokenInfo['worker_id'];
        $all = $request->all();
        if (isset($all['order_id'])) {
//            if (FddUtils::IsOrderBelongToWorker($all['order_id'], $worker_id) == false) {
//                return LMReturn::Error('非所属订单不可进行此操作');
//            }
            $order = Order::find($all['order_id']);
            if ($order->fdd_sign_status == 2 || $order->fdd_sign_status == 4) {
                return LMReturn::Error('该订单非电子签约合同，若要进行电子签约请拒绝后在初审中进行电子签约签署');
            } elseif ($order->fdd_sign_status == 5) {
                return LMReturn::Error('该订单签署失败，请删除后重新生成订单进行电子签约');
            } elseif ($order->fdd_sign_status == 1) {
                return LMReturn::Error('该订单已签署完成，无需重复签署');
            }
            if (isset($all['type']) && $all['type'] == 2) {
                $type = 2;
            } else {
                $type = 1;
            }
            $result = FddUserUtils::CompanyExtsign($all['order_id'], $type);
            if (isset($result['code'])) {
                return $result;
            } else {
                return ['code'=>200, 'msg'=>'success', 'data'=>['url'=>$result]];
            }
        } else {
            return LMReturn::Error('缺少必要传参');
        }
    }

    // 手动签署回调地址
    public function SignNotify(Request $request) {
        $all = $request->all();
        try {
            $transaction_id = $all['transaction_id'];
            $contract_id = $all['contract_id'];
            $result_code = $all['result_code'];
            $result_desc = $all['result_desc'];
            $timestamp = $all['timestamp'];
            $msg_digest = $all['msg_digest'];
            $sha1Str = strtoupper(sha1(\FddConfig::AppSecret . $transaction_id));
            $msg_digests = base64_encode(strtoupper(sha1(\FddConfig::AppId . strtoupper(md5($timestamp)) . $sha1Str)));
            if ($msg_digest == $msg_digests) {
                $order = Order::where('order_no', $contract_id)->first();
                $fdd_record = FddRecord::where('transaction_id', $transaction_id)->where('order_id', $order->id)->first();
                if ($fdd_record->status != 1) {
                    if ($result_code == 3000) {
                        $fdd_record->status = 1;
                        $fdd_record->save();
                        $user_type = $fdd_record->user_type;
                        if ($user_type == 1) {
                            $remark = '客户已签署';
                        } elseif ($user_type == 2) {
                            $remark = '机构方已签署';
                        } elseif ($user_type == 3) {
                            $remark = '担保方已签署';
                        } else {
                            $remark = '电子签署';
                        }
                        $orderRecord = new OrderRecord();
                        $orderRecord->order_id = $order->id;
                        $orderRecord->type = 9;
                        $orderRecord->audit_step = 0;
                        $orderRecord->is_success = 1;
                        $orderRecord->remark = $remark;
                        $orderRecord->save();
                        $user_status = 0;
                        $institution_status = 0;
                        $guarantee_status = 0;
                        $fdd_records = FddRecord::where('order_id', $order->id)->where('status', 1)->get();
                        foreach ($fdd_records as $record) {
                            if ($record['user_type'] == 1) {
                                $user_status = 1;
                            } elseif ($record['user_type'] == 2) {
                                $institution_status = 1;
                            } elseif ($record['user_type'] == 3) {
                                $guarantee_status = 1;
                            }
                        }
                        if ($user_status == 1 && $institution_status == 1 && $guarantee_status == 1) {
                            $fdd_sign_status = 1;
                        } else {
                            $fdd_sign_status = 6;
                        }
                        $order->fdd_sign_status = $fdd_sign_status;
                        if ($fdd_sign_status == 1) {
                            $result = FddUserUtils::AdoutContractFiling($order->id);
                            if ($result == 1) {
                                $order->contract_file = 1;
                            }
                        }
                    } else {
                        $orderRecord = new OrderRecord();
                        $order->fdd_sign_status = 5;
                        $orderRecord->order_id = $order->id;
                        $orderRecord->type = 9;
                        $orderRecord->audit_step = 0;
                        $orderRecord->is_success = 2;
                        $orderRecord->remark = $result_desc;
                        $orderRecord->save();
                    }
                    $order->save();
                }
            }
            return ['code'=>200];
        } catch (\Throwable $th) {
            return ['code'=>200];
        }
    }

    // 合同归档
    public function FddContractFiling(Request $request) {
        // 去验证token值
        $tokenInfo = json_decode($this->verifyTokenLm(), true);
        //判断传递过来的token的code码是否等于400  如果是400的话，提示token不正确
        if ($tokenInfo['code'] == 400) {
            return LMReturn::Error($tokenInfo['msg'], $tokenInfo['code']);
        }
        $worker_id = $tokenInfo['worker_id'];
        $all = $request->all();
        if (isset($all['order_id'])) {
            $order_id = $all['order_id'];
        } else {
            return LMReturn::Error('请选择需归档的合同');
        }
        if (FddUtils::IsOrderBelongToWorker($all['order_id'], $worker_id) == false) {
            return LMReturn::Error('非所属订单不可进行此操作');
        }
        return FddUserUtils::ContractFiling($order_id);
    }

    // 客户查询证书信息
    public function CheckCert(Request $request) {
        // 去验证token值
        $tokenInfo = json_decode($this->verifyTokenLm(), true);
        //判断传递过来的token的code码是否等于400  如果是400的话，提示token不正确
        if ($tokenInfo['code'] == 400) {
            return LMReturn::Error($tokenInfo['msg'], $tokenInfo['code']);
        }
        $all = $request->all();
        if (isset($all['user_id'])) {
            $user_id = $all['user_id'];
        } elseif (isset($tokenInfo['user_id'])) {
            $user_id = $tokenInfo['user_id'];
        } else {
            return LMReturn::Error('未传入用户id');
        }
        $user = User::find($user_id);
        if ($user) {
            $result = FddUserUtils::CheckCertMessage($user['customer_id']);
            if ($result['code'] == 1) {
                $data = $result['data'];
                return LMReturn::Success(json_decode($data, true));
            } else {
                return $result;
            }
        } else {
            return LMReturn::Error('被查询的客户Id不存在');
        }
    }

    // 电子签署出证专业版
    public function OutCert(Request $request) {
        // 去验证token值
        $tokenInfo = json_decode($this->verifyTokenLm(), true);
        //判断传递过来的token的code码是否等于400  如果是400的话，提示token不正确
        if ($tokenInfo['code'] == 400) {
            return LMReturn::Error($tokenInfo['msg'], $tokenInfo['code']);
        }
        $all = $request->all();
        if (isset($all['order_id'])) {
//            if (isset($tokenInfo['worker_id'])) {
//                if (FddUtils::IsOrderBelongToWorker($all['order_id'], $tokenInfo['worker_id']) == false) {
//                    return LMReturn::Error('非所属订单不可进行此操作');
//                }
//            } elseif (isset($tokenInfo['user_id'])) {
//                if (FddUtils::IsOrderBelongToUser($all['order_id'], $tokenInfo['user_id']) == false) {
//                    return LMReturn::Error('非所属订单不可进行此操作');
//                }
//            }
//            else {
//                return LMReturn::Error('登录信息有误');
//            }
            $order_id = $all['order_id'];
            $result = FddUserUtils::OutPutCert($order_id);
            if ($result['code'] == 1000) {
                return LMReturn::Success($result['data']);
            } else {
                return $result;
            }
        } else {
            return LMReturn::Error('未传入合同id');
        }
    }

    /***************电子签约完成*****************/
}
